package com.dirk.happie.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

public class ImageDownloader {
	

	private int width = 150;
	private int height = 150;
	private ConcurrentHashMap<String, Bitmap> bitmapCache = null;
	private Bitmap defaultBitmap = null;
	private boolean isCancelled = false;
	
	ConcurrentHashMap<Integer, AsyncTask<Integer, Void, Bitmap>> threadCache = null;
	ArrayList<DownloadItem> pendingList = new ArrayList<ImageDownloader.DownloadItem>();
	
	
	public ImageDownloader() {
		threadCache = new ConcurrentHashMap<Integer, AsyncTask<Integer,Void,Bitmap>>();
		bitmapCache = new ConcurrentHashMap<String, Bitmap>();
	}
	public void download(final String url, final String cachePath, final ImageView view){
		final String keyString = Common.getMD5(url);
		if(bitmapCache.containsKey(keyString)){
			Bitmap curBitmap = bitmapCache.get(keyString);
			if(!curBitmap.isRecycled()){
				view.setImageBitmap(curBitmap);
			}
			return;
		}
		view.setImageBitmap(defaultBitmap);
		if(threadCache.containsKey(view.hashCode())){
			threadCache.remove(view.hashCode()).cancel(true);
		}
		for(DownloadItem pendingItem : pendingList){
			if(pendingItem.view.hashCode() ==  view.hashCode()){
				pendingItem.url = url;
				pendingItem.cachePath = cachePath;
			}
		}
		if(threadCache.size() > 4){
			DownloadItem pendingItem = new DownloadItem();
			pendingItem.cachePath = cachePath;
			pendingItem.url = url;
			pendingItem.view = view;
			pendingList.add(pendingItem);
			return;
		}
		
		AsyncTask<Integer, Void, Bitmap> downloaderAsync = new AsyncTask<Integer, Void, Bitmap>(){
			@Override
			protected Bitmap doInBackground(Integer... params) {
				Bitmap bitmap = null;
				BitmapFactory.Options options = new BitmapFactory.Options();
				
				if(!isFileExists(cachePath)){
					InputStream in = null;
					try {
						System.out.println("url = "+url);
						in = new java.net.URL(url).openStream();
						bitmap = BitmapFactory.decodeStream(in);
						
						if(bitmap == null){
							Log.e("ImageDownloader", "bitmap is null");
						}
						ByteArrayOutputStream bytes = new ByteArrayOutputStream();
						bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
						File f = new File(cachePath);
						try{
							f.createNewFile();
							FileOutputStream fo = new FileOutputStream(f);
							fo.write(bytes.toByteArray());
							fo.close();
						}catch (Exception e) {
							return bitmap;
						}
							bitmap.recycle();
							
						
					} catch (MalformedURLException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				options.inJustDecodeBounds = true;
				bitmap = BitmapFactory.decodeFile(cachePath, options);
				int inSampleSize = options.outHeight/height;
				inSampleSize = Math.max(inSampleSize, options.outWidth/width);
				inSampleSize = Math.max(inSampleSize, 1);
				options.inJustDecodeBounds = false;
				options.inSampleSize = inSampleSize;
				bitmap = BitmapFactory.decodeFile(cachePath, options);
				try{
//					cache.add(position, bitmap);
				} catch (Exception e) {
					e.printStackTrace();
				}
				
				return bitmap;
			};
			
			@Override
			protected void onPostExecute(Bitmap result) {
				super.onPostExecute(result);
				if(isCancelled){
					if(result != null){
						result.recycle();
					}
				}
				view.setImageBitmap(result);
				bitmapCache.put(keyString, result);
				threadCache.remove(view.hashCode());
				if(pendingList.size() > 0){
					DownloadItem item = pendingList.remove(0);
					download(item.url, item.cachePath, item.view);
				}
			}
			
		};
		downloaderAsync.execute(0);
		threadCache.put(view.hashCode(), downloaderAsync);
		
	}
	
	public void setDefaultBitmap(Bitmap bitmap){
		defaultBitmap = bitmap;
	}
	
	public boolean isFileExists(String path){
		File file = new File(path);
		return file.exists();
	}
	
	private class DownloadItem{
		public String url = null;
		public ImageView view = null;
		public String cachePath = null;
	}
	
	public void clearImages(){
		isCancelled = true;
		Enumeration<String> keysEnum = bitmapCache.keys();
		while(keysEnum.hasMoreElements()){
			String key = keysEnum.nextElement();
			try{
				bitmapCache.remove(key).recycle();
			}catch (Exception e) {
			}
		}
	}
	
}
